import os.path
import pandas as pd
from PySide6.QtWidgets import QWidget,QTableWidgetItem,QMenu,QAbstractItemView,QMessageBox,QFileDialog
from PySide6.QtCore import Qt
import shutil

from views.person.personbase.personbase import Ui_personbase
from views.person.personbase.operationpersonbaseinfoView import OperationPersonBaseInfo
from settings.publicFuncation.exceldownloadimport import OperationModel
from sqlalchemy.orm import Session
from settings.publicvar import engine
from views.person.model.person import PersonBaseInfo

class PersonBaseInfoView(QWidget,Ui_personbase):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.personbaseinfotable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.personbaseinfotable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.personbaseinfotable.setContextMenuPolicy(Qt.CustomContextMenu)
        self.personbaseinfotable.customContextMenuRequested.connect(self.generate_menu)
        self.loadTableData()

        self.addpersonbaseinfo.clicked.connect(self.addFun)
        self.serearchbtn.clicked.connect(self.sereachFun)
        self.downloadmodle.clicked.connect(self.downloadmodleFun)
        self.importbtn.clicked.connect(self.importdataFun)
        self.sereachedit.editingFinished.connect(self.sereachFun)

    # 表结构设置
    def SetTableStructure(self,data):
        self.personbaseinfotable.setRowCount(len(data))
        for i, personbaseinfo in enumerate(data):
            ind = QTableWidgetItem(str(personbaseinfo.id))
            self.personbaseinfotable.setItem(i, 0, ind)
            name = QTableWidgetItem(personbaseinfo.name)
            self.personbaseinfotable.setItem(i, 1, name)
            IDcard = QTableWidgetItem(personbaseinfo.IDcard)
            self.personbaseinfotable.setItem(i, 2, IDcard)
            iphone = QTableWidgetItem(personbaseinfo.iphone)
            self.personbaseinfotable.setItem(i, 3, iphone)

    # 加载表格数据
    def loadTableData(self):
        with Session(engine) as session,session.begin():
            personbaseinfos = session.query(PersonBaseInfo).all()
            self.SetTableStructure(personbaseinfos)

    # 菜单数据
    def generate_menu(self,pos):
        menu = QMenu()
        viewitem = menu.addAction('查看')
        changeitem = menu.addAction('修改')
        deletitem = menu.addAction('删除')
        action = menu.exec(self.personbaseinfotable.mapToGlobal(pos))
        posrow = self.personbaseinfotable.currentRow()
        columns = self.personbaseinfotable.columnCount()
        data = [self.personbaseinfotable.item(posrow, i).text() for i in range(columns)]
        if action == changeitem:
            change = OperationPersonBaseInfo('change',data)
            change.exec()
        elif action == deletitem:
            delete = OperationPersonBaseInfo('delete',data)
            delete.exec()
        elif action == viewitem:
            view = OperationPersonBaseInfo('view',data)
            view.exec()
        self.loadTableData()


    # 搜索
    def sereachFun(self):
        sereachedit = self.sereachedit.text().strip()
        if sereachedit == '':
            QMessageBox.critical(None, '错误', '搜索框不能为空！')
            self.loadTableData()
        else:
            with Session(engine) as session, session.begin():
                sereachName = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.name.like('%' + sereachedit + '%')).all()
                sereachIDcard = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.IDcard.like('%' + sereachedit + '%')).all()
                sereachiphone = session.query(PersonBaseInfo).filter(
                    PersonBaseInfo.iphone.like('%' + sereachedit + '%')).all()
                sereachData = sereachName + sereachIDcard + sereachiphone
                if sereachedit:
                    self.SetTableStructure(sereachData)

    # 模板下载
    def downloadmodleFun(self):
        OperationModel().downloadmodleFun('人员基本信息模板.xlsx')

    # 导入数据
    def importdataFun(self):
        names=['idx', 'name', 'IDcard', 'iphone']
        dtypes = {'IDcard': str, 'iphone': str}
        data = OperationModel().importdataFun(names,dtypes)
        with Session(engine) as session,session.begin():
            exist_personbase = session.query(PersonBaseInfo).filter(PersonBaseInfo.IDcard.in_(data.IDcard.to_list())).all()
            exist_idcard = [item.IDcard for item in exist_personbase]
            save_personbase = data[~data['IDcard'].isin(exist_idcard)].to_dict('records')
            personbases = [PersonBaseInfo(**item) for item in save_personbase]
            session.add_all(personbases)
            QMessageBox.information(None,'导入信息','你导入成功%s条，失败%s条，明细如下！'%(len(personbases),(len(data)-len(personbases))))
        self.loadTableData()

    def addFun(self):
        operation_person = OperationPersonBaseInfo('add',False)
        operation_person.exec()
        self.loadTableData()

